// 添加 JsonDB 引用
const JsonDB = require("../json-db");
const path = require("path");
let db = null;

// 将初始化数据库的代码提取为单独的函数
async function initializeDB() {
  const dataPath = path.resolve("./data");
  console.log("数据库存储路径:", dataPath);

  return new JsonDB({
    storage: {
      path: dataPath,
      mode: "hybrid",
    },
    backup: {
      enabled: true,
      interval: 3600000,
      keepCount: 5,
    },
    logger: {
      level: "debug",
      file: path.join(dataPath, "db.log"),
      console: true,
    },
  });
}

// 生成数据函数
function generateStudentData(count, startIndex = 0) {
  const surnames = ["张", "李", "王", "刘", "陈", "杨", "黄", "赵", "吴", "周"];
  const names = ["伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "洋"];
  const classes = ["高三一班", "高三二班", "高三三班", "高三四班"];
  const genders = ["男", "女"];

  return Array.from({ length: count }, (_, index) => {
    const actualIndex = startIndex + index;
    const surname = surnames[Math.floor(Math.random() * surnames.length)];
    const name = names[Math.floor(Math.random() * names.length)];
    const gender = genders[Math.floor(Math.random() * genders.length)];
    const classIndex = Math.floor(Math.random() * classes.length);

    function generateScore() {
      const mean = 80;
      const stdDev = 8;
      let score;
      do {
        const u1 = Math.random();
        const u2 = Math.random();
        const z = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(2.0 * Math.PI * u2);
        score = Math.round(mean + stdDev * z);
      } while (score < 60 || score > 100);
      return score;
    }

    return {
      学号: 1001 + actualIndex,
      姓名: surname + name,
      性别: gender,
      年龄: Math.floor(Math.random() * 2) + 17,
      班级: classes[classIndex],
      语文: generateScore(),
      数学: generateScore(),
      英语: generateScore(),
      物理: generateScore(),
      化学: generateScore(),
      生物: generateScore(),
    };
  });
}

// 插入数据的函数
async function insertStudentData(db, count, batchSize = 1000) {
  console.log(`开始插入${count}条数据，每批${batchSize}条`);
  
  for(let i = 0; i < count; i += batchSize) {
    const currentBatchSize = Math.min(batchSize, count - i);
    const batchData = generateStudentData(currentBatchSize, i);
    
    await db.插入数据({
      表名: "学员成绩表",
      数据: batchData,
      模式: "批量",
    });
    
    console.log(`已插入 ${i + currentBatchSize}/${count} 条数据`);
  }
}

// 主函数
async function main() {
  try {
    db = await initializeDB();
    
    // 检查元数据
    const metadata = await db.读取元数据();
    console.log("元数据:", JSON.stringify(metadata, null, 2));
    
    
    // 检查表信息
    const tableInfo = await db.获取表信息('学员成绩表');
    console.log("获取到的表信息:", tableInfo);
    
    await insertStudentData(db, 33450, 1000);
    console.log("数据插入完成");
  } catch (error) {
    console.error("执行失败:", error);
  }
}

// 运行主函数
main().catch((error) => {
  console.error("程序执行失败:", error);
}); 